package com.sgv.model.persistence;

import java.math.BigInteger;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.Query;

import com.archtecture.control.exceptions.NegocioException;
import com.archtecture.control.facedes.PersistenceFacadeLocal;
import com.sgv.model.entities.UsuarioModel;

@Stateless(name = UsuarioFacadeLocal.JNDI_NAME)
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
@TransactionManagement(TransactionManagementType.CONTAINER)
public class UsuarioFacadeBean implements UsuarioFacadeLocal {

	@EJB
	private PersistenceFacadeLocal persistenceFacade;

	@Resource
	private EJBContext ejbContext;

	@Override
	public UsuarioModel obterUsuarioLogado() throws NegocioException {

		UsuarioModel lUsuario = new UsuarioModel();
		lUsuario.setLogin(ejbContext.getCallerPrincipal().getName());

		lUsuario = persistenceFacade.pesquisarUnico(lUsuario, "getListPapel");

		return lUsuario;
	}

	@Override
	public boolean verificarPermissao(String... pPerfis) {

		for (String lPerfilLoop : pPerfis) {
			if (ejbContext.isCallerInRole(lPerfilLoop)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean verificaUsuarioSenhaPadrao() throws NegocioException {
		StringBuilder lSb = new StringBuilder().append(
				"SELECT CASE U.HS_SENHA WHEN 'WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U=' THEN TRUE ELSE FALSE END FROM TBUSUARIO U WHERE U.CD_USUARIO = ")
				.append(obterUsuarioLogado().getCodigo());

		Query query = persistenceFacade.getManager().createNativeQuery(lSb.toString());
		return (BigInteger) query.getSingleResult() == BigInteger.ONE;
	}

}
